/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package br.com.ucb.game8numbers.tree;

import br.com.ucb.game8numbers.service.operator.Operator;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

/**
 *
 * @author JessicaLuanne
 */
public class PuzzleStateTreeNode{

    private String[][] state;
    private Operator operator;
    private PuzzleStateTreeNode parent;
    private Set<PuzzleStateTreeNode> children;

    public PuzzleStateTreeNode() {
        setChildren(new HashSet<PuzzleStateTreeNode>());
    }

    public int getDegree() {
       return getChildren().size();
    }

    public boolean addChild(PuzzleStateTreeNode n) {
        return children.add(n);
    }

    public boolean addChilds(List<PuzzleStateTreeNode> nodes) {
        return children.addAll(nodes);
    }

    public boolean removeChild(PuzzleStateTreeNode n) {
        return children.remove(n);
    }

    public Iterator<PuzzleStateTreeNode> iterator() {
        return children.iterator();
    }

    public int getHeight()
    {
        PuzzleStateTreeNode higher = getHigherChild();
        return (higher != null ? higher.getHeight() : 0) + 1;
    }

    @Override
    public boolean equals(Object obj) {
        if (!(obj instanceof PuzzleStateTreeNode)) {
            return false;
        }
        PuzzleStateTreeNode other = (PuzzleStateTreeNode) obj;
        if ((this.state == null && other.state != null) || (this.state != null && !Arrays.equals(this.state, other.state))) {
            return false;
        }
        return true;
    }

    @Override
    public int hashCode() {
        int hash = 0;
        hash += (state != null ? state.hashCode() : 0);
        return hash;
    }

    public boolean isLeaf() {
        return getChildren()==null || getChildren().isEmpty();
    }

    public Set<PuzzleStateTreeNode> getChildren() {
        return children;
    }

    public void setChildren(Set<PuzzleStateTreeNode> children) {
        this.children = children;
    }

    public PuzzleStateTreeNode getParent() {
        return parent;
    }

    public void setParent(PuzzleStateTreeNode parent) {
        this.parent = parent;
    }

    public String[][] getState() {
        return state;
    }

    public void setState(String[][] state) {
        this.state = state;
    }

    public Operator getOperator() {
        return operator;
    }

    public void setOperator(Operator operator) {
        this.operator = operator;
    }

    private PuzzleStateTreeNode getHigherChild() {
        PuzzleStateTreeNode higher = null;
        for (PuzzleStateTreeNode n : getChildren()) {
            if(higher == null || n.getHeight() < higher.getHeight())
            {
                higher = n;
            }
        }
        return higher;
    }

}
